#coding=utf-8
from django.db import models
from django.contrib.auth.models import User

class RelationManager(models.Manager):
    def isblock(self, from_user, to_user):
        try:
            relation = self.get(from_user=from_user, to_user=to_user)
            if relation.type == Relation.BLOCK:
                return True
        except Relation.DoesNotExist:
            pass
        return False
         
    def isfriend(self, from_user, to_user):
        try:
            relation1 = self.get(from_user=from_user, to_user=to_user)
            relation2 = self.get(from_user=to_user, to_user=from_user)
            if relation1.type == Relation.FRIEND and relation2.type == Relation.FRIEND:
                return True
        except Relation.DoesNotExist:
            pass
        return False

class Relation(models.Model):
    REQ_FRIEND = 0
    FRIEND = 1
    BLOCK = 2
    RELATION_TYPE = ((FRIEND, u'朋友'), (REQ_FRIEND, u'朋友请求'), (BLOCK, u'阻止'),)

    from_user = models.ForeignKey(User, related_name="+")
    to_user = models.ForeignKey(User, related_name="+")
    type = models.IntegerField(choices=RELATION_TYPE, default=FRIEND, verbose_name=u"用户关系") 
    created_time = models.DateTimeField(auto_now_add=True)	

    objects = RelationManager()

    class Meta:
        verbose_name = u'用户关系'
        verbose_name_plural = u'用户关系列表'
        db_table = "t_relation"
        unique_together = ("from_user", "to_user")  # 两个人之间只能保证一种关系的存在
        ordering = ["-created_time"]
